import {
  AlipayCircleOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import { Helmet, useModel } from '@umijs/max';
import { Alert, App, Tabs } from 'antd';
import { createStyles } from 'antd-style';
import React, { useEffect, useState } from 'react';
import { flushSync } from 'react-dom';
import { authService } from '@/authService';
import { AJCaptchaSlider, Footer } from '@/components';
import { login } from '@/services/user/login';
import Settings from '../../../../config/defaultSettings';

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
  };
});

const ActionIcons = () => {
  const { styles } = useStyles();

  return (
    <>
      <AlipayCircleOutlined
        key="AlipayCircleOutlined"
        className={styles.action}
      />
      <TaobaoCircleOutlined
        key="TaobaoCircleOutlined"
        className={styles.action}
      />
      <WeiboCircleOutlined
        key="WeiboCircleOutlined"
        className={styles.action}
      />
    </>
  );
};

const _LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  // 验证码相关
  const [size, setSize] = useState<'default' | 'large' | 'big'>('default');
  const [showCaptcha, setShow] = useState<boolean>(false);
  const [loginValues, setLoginValues] = useState<UserTypes.LoginParams | null>(
    null,
  );
  // 登录相关
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');
  const { styles } = useStyles();
  const { message } = App.useApp();

  // 调用获取用户信息接口
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  const handleSubmit = async (values: UserTypes.LoginParams) => {
    // 登录
    const token = await login(values);
    // 同步到本地存储，确保刷新后不丢失
    authService.saveTokens(
      token.accessToken,
      token.refreshToken,
      token.expireTime,
    );
    const defaultLoginSuccessMessage = '登录成功！';
    message.success(defaultLoginSuccessMessage);
    // 获取用户信息
    await fetchUserInfo();
    console.log('用户信息获取结果：', initialState?.currentUser); // 若为 undefined，说明获取失败
    // 解析当前页面的 URL 获取 URL 中的查询参数部分
    const urlParams = new URL(window.location.href).searchParams;
    // 获取名为 "redirect" 的查询参数值进行跳转，没有则跳转根目录
    window.location.href = urlParams.get('redirect') || '/';
  };

  const resizeUpdate = () => {
    // 通过事件对象获取浏览器窗口的宽度
    const w = window.innerWidth;
    if (w < 480) setSize('default');
    else if (w < 980) setSize('big');
    else setSize('large');
  };

  // 钩子函数，在页面挂载时执行一次，[依赖项数组] 依赖项数组变化时会执行
  useEffect(() => {
    resizeUpdate();
    // 页面变化时获取浏览器窗口的大小
    window.addEventListener('resize', resizeUpdate);

    return () => {
      // 组件销毁时移除监听事件
      window.removeEventListener('resize', resizeUpdate);
    };
  }, []);

  // 验证码校验成功时执行
  const onSuccess = async (token: string) => {
    // 隐藏验证码组件
    setShow(false);

    // 检查是否有登录参数，有则调用登录接口
    if (loginValues) {
      // 调用登录接口，可将验证码 token 传入登录参数（如果需要）
      loginValues.captchaVerification = token;
      await handleSubmit(loginValues);
    }
  };

  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {'登录'}
          {Settings.title && ` - ${Settings.title}`}
        </title>
      </Helmet>

      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        {/* 验证码组件 */}
        <AJCaptchaSlider
          title="Verify Modal"
          tips="Slide the slider to the right"
          refreshText="Refresh"
          show={showCaptcha}
          onSuccess={onSuccess}
          size={size}
          hide={() => setShow(false)}
        />

        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="/logo.svg" />}
          title="Ant Design"
          subTitle={'Ant Design 是西湖区最具影响力的 Web 设计规范'}
          initialValues={{
            autoLogin: true,
          }}
          actions={[
            <span key="loginWith">其他登录方式</span>,
            <ActionIcons key="icons" />,
          ]}
          onFinish={async (values) => {
            // await handleSubmit(values as API.LoginParams);
            // 保存表单提交的参数
            setLoginValues(values as UserTypes.LoginParams);
            // 显示验证码组件
            setShow(true);
          }}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'account',
                label: '账户密码登录',
              },
              {
                key: 'mobile',
                label: '手机号登录',
              },
            ]}
          />
          {type === 'account' && (
            <>
              <ProFormText
                name="username"
                initialValue="17677976855"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder="用户名"
                rules={[
                  {
                    required: true,
                    message: '请输入用户名!',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                initialValue="123456"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder="密码"
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                ]}
              />
            </>
          )}

          {type === 'mobile' && (
            <ProFormText
              fieldProps={{
                size: 'large',
                prefix: <MobileOutlined />,
              }}
              name="mobile"
              placeholder="手机号"
              rules={[
                {
                  required: true,
                  message: '请输入手机号！',
                },
                {
                  pattern: /^1\d{10}$/,
                  message: '手机号格式错误！',
                },
              ]}
            />
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <ProFormCheckbox noStyle name="autoLogin">
              "自动登录"
            </ProFormCheckbox>
            <a
              style={{
                float: 'right',
              }}
            >
              "忘记密码"
            </a>
          </div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
